package org.pentaho.cubic.client.perspective.tabs;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.Widget;

public class CubicTabBarWidget extends HorizontalPanel{

	private CubicTabLayoutPanel tabPanel;
	private Widget tabContent;
	private Label textLabel = new Label();
	private Button closeTabButton = new Button();
	private String fullText;
	private boolean canClose;

	public CubicTabBarWidget(String text, String title, CubicTabLayoutPanel panel, Widget content, Boolean closable) {
		
		this.setHeight("25px");
		this.setVerticalAlignment(ALIGN_MIDDLE);
		
		this.tabPanel = panel;
		this.tabContent = content;
		this.canClose = closable;

		this.setLabelText(text);
		this.setLabelTooltip(title);
		textLabel.setWordWrap(false);
		this.add(textLabel);

		if (closable) {
			closeTabButton.setText(" X ");
			closeTabButton.setTitle("Close this tab");
			closeTabButton.addClickHandler(new ClickHandler() {
				public void onClick(ClickEvent event) {
					closeTab();
				}
			});
			this.add(closeTabButton);
		}
	}

	public void setLabelText(String text) {
		String trimmedText = text.substring(0, Math.min(15, text.length()));
		fullText = text;
		if (!trimmedText.equals(text)) {
			trimmedText += ".."; 	//$NON-NLS-1$
		}
		textLabel.setText(trimmedText);
	}

	public void setLabelTooltip(String tooltip) {
		textLabel.setTitle(tooltip);
	}

	public String getText() {
		return fullText;
	}
	
	public boolean closable(){
		return canClose;
	}

	public void closeTab() {
		if (canClose) {
			// Move current tab selection
			if (tabPanel.getSelectedIndex() == tabPanel.getWidgetIndex(tabContent)) {
				if (tabPanel.getSelectedIndex() == 0) {
					tabPanel.selectTab(tabPanel.getSelectedIndex() + 1);
				} else if (tabPanel.getSelectedIndex() > 0) {
					tabPanel.selectTab(tabPanel.getSelectedIndex() - 1);
				}
			}
			tabPanel.remove(tabPanel.getWidgetIndex(tabContent));
		}
	}

}
